﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Usermanagment.DBConnection;


namespace LSProtocol {
	
	public enum Errors
	{
		ERR_UsernameIsTaken,
		ERR_UsernameLoggedIn,
		ERR_UsernameNotExists,
		ERR_UsernameRegistered,
		ERR_UsernameToolong,
		ERR_UsernameTooShort,
		ERR_UsernameIlChars,
		ERR_PassTooShort,
		ERR_UserBanned,
		ERR_BadPassword,
		ERR_PassIlChars
	}


	public abstract class Protocol {
		protected DBConnect dbc;
		protected DBDatafetch dft;
		protected UserCreate uc;
		public String error;
		protected Boolean userNameLong(String user)
		{
			return (user.Length >= 18);
		}

		protected Boolean userNameShort(String user)
		{
			return (user.Length < 6);
		}

		protected Boolean badChars(String user)
		{
			Boolean ans = false;
			Regex re = new Regex("^[A-Za-z0-9]+$");
			if (!re.IsMatch(user))
				ans = true;
			return ans;
		}

		protected Boolean shortPass(String pass)
		{
			return (pass.Length < 8);
		}
	}

	public class SignInProtocol : Protocol {

		
		public SignInProtocol(DBConnect dbConnection) {
			this.dbc = dbConnection;
			dft = new DBDatafetch(dbc);
			uc = new UserCreate(dbc);
			
		}
		public Errors signIn(string user, string pass) {
			if (badChars(user))
				return Errors.ERR_UsernameIlChars;
			if (badChars(pass))
				return Errors.ERR_PassIlChars;
			string resPass = dft.fetchPass(user);
			if (resPass.Length == 0) 
			{
				return Errors.ERR_UsernameNotExists;
			}
			else if (!resPass.Equals(pass)) 
			{
				error = pass;
				return Errors.ERR_BadPassword;
			}
			else {
				if(dft.canConnect(user) > 0)
					return Errors.ERR_UsernameLoggedIn;
				return Errors.ERR_UserBanned;
			}
		}
	}

	public class SignUpProtocol : Protocol {

		public SignUpProtocol(DBConnect dbConnection) {
			this.dbc = dbConnection;
			dft = new DBDatafetch(dbc);
			uc = new UserCreate(dbc);
		}
		public Errors signUp(string user, string pass) {			
			if (badChars(user))
				return Errors.ERR_UsernameIlChars;
			if (badChars(pass))
				return Errors.ERR_PassIlChars;
			int id = dft.getID(user);
			if (id > 0) {
				return Errors.ERR_UsernameIsTaken;
			}
			if (userNameLong(user))
				return Errors.ERR_UsernameToolong;
			if (userNameShort(user))
				return Errors.ERR_UsernameTooShort;
			if (shortPass(pass))
				return Errors.ERR_PassTooShort;
			uc.insertUser(user, pass);		    
			return Errors.ERR_UsernameRegistered;
		}

		
	}


}
